package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet("/selectByPageAndConditionServlet")
public class SelectByPageAndConditionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.接收参数：当前页码 和 每页显示条数，查询条件对象
        String currentPageStr = request.getParameter("currentPage");
        String pageSizeStr = request.getParameter("pageSize");
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String statusStr = request.getParameter("status");
        System.out.println("brandName = " + brandName);

        // 处理get请求乱码
        // brandName = URLEncoder.encode(URLDecoder.decode(brandName, "ISO-8859-1"), "UTF-8");
        // companyName = URLEncoder.encode(URLDecoder.decode(companyName, "ISO-8859-1"), "UTF-8");

        brandName = URLDecoder.decode(URLEncoder.encode(brandName, "ISO-8859-1"), "UTF-8");
        companyName = URLDecoder.decode(URLEncoder.encode(companyName, "ISO-8859-1"), "UTF-8");

        // 将字符串转成数字
        int currentPage = Integer.parseInt(currentPageStr); // "3" -> 3
        int pageSize = Integer.parseInt(pageSizeStr); // "5" -> 5

        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        if (statusStr.length() > 0) {
            int status = Integer.parseInt(statusStr);
            brand.setStatus(status);
        }

        // 2.调用service查询，返回PageBean
        BrandService brandService = new BrandServiceImpl();
        PageBean pageBean = brandService.selectByPageAndCondition(currentPage, pageSize, brand);

        // 3.将PageBean转为JSON，写回客户端
        String json = JSON.toJSONString(pageBean);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(json);
    }
}
